<template>
	<view class="content">
		<view class="headerView">
			<image src="/static/Bank_student.png" class="icon"></image>
			<text class="">学生信息</text>
		</view>
		
		<van-field
			class="itemView"
			v-model="userName"
			style="margin-top: 0;"
		    label="学生姓名"
		    right-icon="./static/Bank_edit.png"
		    placeholder="请输入姓名"
			input-align="right"
		/>
		<van-field
			class="itemView"
		    v-model="userCertNum"
		    label="学生证件号"
		    right-icon="./static/Bank_edit.png"
		    placeholder="请输入学生证件号"
			input-align="right"
		/>
		
		<view class="headerView">
			<image src="/static/Bank_parent.png" class="icon"></image>
			<text class="">签约持卡人信息</text>
		</view>
		<van-field
			class="itemView"
		    v-model="signName"
		    label="持卡人姓名"
		    right-icon="./static/Bank_edit.png"
		    placeholder="请输入持卡人姓名"
			input-align="right"
		/>
		<van-field
			class="itemView"
		    v-model="signCertNum"
		    label="持卡人证件号"
		    right-icon="./static/Bank_edit.png"
		    placeholder="请输入持卡人证件号"
			input-align="right"
		/>
		<van-field
			class="itemView"
		    v-model="signPhone"
		    label="持卡人手机号"
		    right-icon="./static/Bank_edit.png"
		    placeholder="请输入持卡人手机号"
			input-align="right"
		/>
		
		<view class="buttomView" @click="nextClick">
			下一步
		</view>
	</view>
</template>

<script>
	const env = process.env
	import { Field, Icon } from 'vant';
	export default {
		components: {
			[Field.name]: Field,
		},
		data() {
			return {
				"organId": "",
				"userName": "",
				"userCertNum": "",
				
				"signName": "",
				"signCertNum": "",
				"signPhone": ""
			}
		},
		onLoad(res) {
			
			if (!res['organId']) {
				this.$data.organId = '1'
			} else {
				this.$data.organId = res['organId']
			}
			console.log('-=-=-=-=--==-=', this.$data.organId)
		},
		methods: {
			nextClick() {
				console.log("下一步")
				console.log(JSON.parse(JSON.stringify(this.$data)))
				if (!this.$data.organId) {
					uni.showToast({
						title: '缺少organId',
						icon: 'none'
					})
					return
				}
				if (!this.$data.userName) {
					uni.showToast({
						title: '请填写学生姓名',
						icon: 'none'
					})
					return
				}
				if (!this.$data.userCertNum) {
					uni.showToast({
						title: '请填写学生证件号',
						icon: 'none'
					})
					return
				}
				
				
				if (!this.$data.signName) {
					uni.showToast({
						title: '请填写持卡人人姓名',
						icon: 'none'
					})
					return
				}
				if (!this.$data.signCertNum) {
					uni.showToast({
						title: '请填写持卡人证件号',
						icon: 'none'
					})
					return
				}
				if (!this.validateIDCard(this.$data.signCertNum)) {
					uni.showToast({
						title: '请填写正确持卡人证件号',
						icon: 'none'
					})
					return
				}
				if (!this.$data.signPhone) {
					uni.showToast({
						title: '请填写持卡人手机号',
						icon: 'none'
					})
					return
				}
				if (!this.validatePhone(this.$data.signPhone)) {
					uni.showToast({
						title: '请填写正确手机号',
						icon: 'none'
					})
					return
				}
				this.network_apply()
			},
			// 验证手机号码
			validatePhone(phone) {
				const regex = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
				return regex.test(phone)
			},
			// 验证身份证
			validateIDCard(idCard) {
				// 1. 基本格式校验
				const regex = /^\d{17}[\dXx]$/;
				if (!regex.test(idCard)) return false;
				
				// 2. 校验省份码（前2位）
				const provinceCode = idCard.substring(0, 2);
				const validProvinceCodes = [
					'11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33',
					'34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50',
					'51', '52', '53', '54', '61', '62', '63', '64', '65'
				];
				if (!validProvinceCodes.includes(provinceCode)) return false;

				// 3. 校验出生日期
				const birthDate = idCard.substring(6, 14);
				const year = parseInt(birthDate.substring(0, 4));
				const month = parseInt(birthDate.substring(4, 6)) - 1;
				const day = parseInt(birthDate.substring(6, 8));
				const date = new Date(year, month, day);
				if (
					date.getFullYear() !== year ||
					date.getMonth() !== month ||
					date.getDate() !== day
				) {
					return false;
				}
			
				// 4. 计算校验位
				const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
				const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
				let sum = 0;
				for (let i = 0; i < 17; i++) {
					sum += parseInt(idCard[i]) * weights[i];
				}
				const calculatedCode = checkCodes[sum % 11];
				return calculatedCode === idCard[17].toUpperCase();
			},
			
			// 网络请求
			// 申请
			network_apply() {
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				let data = {
					"organId": this.$data.organId,
					"userName": this.$data.userName,
					"userCertNum": this.$data.userCertNum,
					
					"signName": this.$data.signName,
					"signCertType": "01",
					"signCertNum": this.$data.signCertNum,
					"signPhone": this.$data.signPhone
				}
				
				// let url = 'http://192.168.2.123:8888/info/order/unipay-sign'
				let url = `https://api.e-ky.cn/info/order/unipay-sign`
				uni.request({
					url: url,
					method: "POST",
					data: data,
					success: (res) => {
						console.log(res['data'])
						if (res['data']['success']) {
							let url = res['data']['data']['url']
							uni.setStorageSync('open_url', url);
							
							console.log('url=', url)
							setTimeout(function() {
								window.open(url, '_self');
							}, 500);
							// this.network_accessToken()
						} else {
							uni.showToast({
								title: res['data']['message'],
								icon: 'none'
							})
						}
					},
					fail: (res) => {
						console.log(res)
					},
					complete: (res) => {
						uni.hideLoading()
					}
				})
			},
			
			// 获取Access_token
			network_accessToken() {
				let baseURL = `https://h5.e-ky.cn/baidubce/oauth/2.0/token`
				let grant_type = 'client_credentials'
				let client_id = 'HbzDNoWCBqsoRnsVSFTIbAg4'
				let client_secret = '7RDoiaQXRIfrpha7hLwOaxEUlV2rz3iy'
				let url = `${baseURL}?grant_type=${grant_type}&client_id=${client_id}&client_secret=${client_secret}`

				let header = {
					'Content-Type': 'application/json',
					'Accept': 'application/json'
				}
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				uni.request({
					url: url,
					method: 'POST',
					header: header,
					success: (res) => {
						if (res['statusCode'] == 200) {
							this.network_verifyToken(res['data']['access_token'])
						}
					},
					fail: (error) => {
					},
					complete: (res) => {
						uni.hideLoading()
					}
				})
			},
			
			// 获取verify_token
			network_verifyToken(access_token) {
				console.log(access_token)
				let url = `https://h5.e-ky.cn/baidubce/rpc/2.0/brain/solution/faceprint/verifyToken/generate?access_token=${access_token}`
				let success_url = uni.getStorageSync('open_url');
				let failed_url = "https://h5.e-ky.cn/BankSigning"
				
				let data = {
					plan_id: '23832',
					redirect_config: {
						success_url: success_url,
						failed_url: failed_url
					}
				}
				let header = {
					'Content-Type': 'application/json'
				}
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				uni.request({
					url: url,
					method: 'POST',
					data: data,
					header: header,
					success: (res) => {
						if (res['statusCode'] == 200) {
							if (res['data']['success']) {
								let verify_token = res['data']['result']['verify_token']
								
								let url = `https://brain.baidu.com/face/print/?token=${verify_token}`
								// uni.navigateTo({
								// 	url: '/pages/webView/webView?url=' + encodeURIComponent(url)
								// })
								console.log('url=', url)
								uni.setStorageSync('face_url', url);
								setTimeout(function() {
									window.open(url, '_self');
								}, 500);
							}
						}
					},
					fail: (error) => {
						
					},
					complete: (res) => {
						console.log(res)
						uni.hideLoading()
					}
				})
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		/* justify-content: center; */
		background-color: #F7F9FD;
		width: 100%;
	}
	.headerView {
		display: flex;
		align-items: center;
		width: 100%;
		min-height: 100rpx;
	}
	.headerView image {
		width: 40rpx;
		height: 40rpx;
		margin-left: 30rpx;
		margin-right: 16rpx;
	}
	.headerView text {
		font-size: 30rpx;
		font-weight: 900;
	}
	
	.itemView {
		/* display: flex; */
		/* align-items: center; */
		width: 690rpx;
		background-color: white;
		min-height: 80rpx;
		border-radius: 20rpx;
		font-size: 30rpx;
		margin-top: 20rpx;
	}
	.van-field__control {
		font-size: 30rpx !important;
	}
	.buttomView {
		display: flex;
		position: fixed;
		align-items: center;
		justify-content: center;
		color: white;
		font-weight: bold;
		border-radius: 45rpx;
		height: 90rpx;
		width: 690rpx;
		background-color: #508BFF;
		bottom: 100rpx;
	}
</style>
